<?php

include_once "quickcrud_connect.php";
include_once "quickcrud_common.php";
include "CF_mysql_com.php";
include_once "CF_all_com.php";

// CT 2009-02-27 - Added classlib_path as subpath for createion of common elements.  Also added jscalendar subdirectory

if (!isset($_REQUEST['project_id'])  ){
	print 'Please select or create a project first';
	print "<a href='switchboard.php?project_id=$project_id'> Back to Switchboard</a>";
	exit;
}

	$project_id = $_REQUEST['project_id'];


	$qry_project_info = "SELECT * FROM projects WHERE project_id = $project_id";

	$project_info = get_array_query($qry_project_info);
	$project_db = $project_info[1]['project_db'];
	$project_path = $project_info[1]['project_path'];
	$project_server = $project_info[1]['project_server'];
	$project_login = $project_info[1]['project_login'];
	$project_pass = $project_info[1]['project_pass'];
    $project_name = $project_info[1]['project_name'];
	$class_subpath = $project_info[1]['class_subpath'];
	$template_dir = $project_info[1]['template_dir'];
	

	
    // This will be the path without the last slash
    $project_path = PROJECT_SUBPATH . $project_path;


	//print_r($project_info);
	
// if path not exists, create
	if(!file_exists($project_path))
	{
		mkdir($project_path);
	}

	//create jscalendar subpath as jscalendar
	$jscal_path = $classlib_path = $project_path . '/' . 'jscalendar';
	
	if(!file_exists($jscal_path))
	{
		mkdir($jscal_path);
		mkdir($jscal_path . '/lang');
	}
	
	
	
	
	if(!empty($class_subpath)){
		$classlib_path = $project_path . '/' . $class_subpath;
		if(!file_exists($classlib_path)){
			mkdir($classlib_path);
		}
		
	}else{
		$classlib_path = $project_path;
	}

// IS THIS USED???		
// copy templates folder recursivaly
//	$qc_tpls_path = $project_path . '/' . $template_dir;
//	if(!file_exists($qc_tpls_path))
//	{
//		mkdir($qc_tpls_path);
//	}
//	smartCopy($template_dir,$qc_tpls_path);
	
	
	smartCopy($template_dir . "/tplcommon", $project_path . "/tplcommon");	
	
	//copy($template_dir . "qctstyle.css", $project_path . "/qctstyle.css");
	//copy($template_dir . "leftmenu.php", $project_path . "/leftmenu.php");
	//copy($template_dir . "qclogo.gif", $project_path . "/qclogo.gif");	
// copy Common Library files 
	smartCopy("use_library/CFclass",$project_path ."/CFclass");
// copy Common Library files 

/*	copy("CFclass/CF_mysql_com.php",$classlib_path . "/CF_mysql_com.php");
	copy("CFclass/CFmultiselect.js",$classlib_path . "/CFmultiselect.js");
	copy("CFclass/ajtable.js",$classlib_path . "/ajtable.js");
	copy("CFclass/CF_process_class.php",$classlib_path . "/CF_process_class.php");
	copy("CFclass/CF_class_com.php",$classlib_path . "/CF_class_com.php");
	copy("CFclass/CF_support.php",$classlib_path . "/CF_support.php");
	copy("CFclass/CF_form_class.php",$classlib_path . "/CF_form_class.php");
    copy("CFclass/commonctls.css",$classlib_path . "/commonctls.css");
    copy("CFclass/CF_bodyjs.js",$classlib_path . "/CF_bodyjs.js");
*/	
	
// copy jscalendar files
	copy("jscalendar/calendar.js",$jscal_path . "/calendar.js");
	copy("jscalendar/calendar_stripped.js",$jscal_path . "/calendar_stripped.js");
	copy("jscalendar/calendar-setup.js",$jscal_path . "/calendar-setup.js");
	copy("jscalendar/calendar-win2k-cold-1.css",$jscal_path . "/calendar-win2k-cold-1.css");
	copy("jscalendar/lang/calendar-en.js",$jscal_path . "/lang/calendar-en.js");	
	copy("jscalendar/img.gif",$jscal_path . "/img.gif");
	
// create connect page
	$connect_stuff = make_connect_page($project_id,"crazyname.php");
	file_put_contents($project_path .'/' . $project_name . '_connect.php', $connect_stuff);
    $result =  "Created projet base files in $project_path";

	
	$result = urlencode($result);
	$header_text = "Location: leftmenu.php?project_id=$project_id&result=$result";
	header($header_text); /* Redirect browser */
	exit;
	
function make_connect_page($project_id, $targetfile){

	$qry_project_info = "SELECT * FROM projects WHERE project_id = $project_id";

	$project_info = get_array_query($qry_project_info);
	$project_db = $project_info[1]['project_db'];
	$project_path = $project_info[1]['project_path'];
	$project_server = $project_info[1]['project_server'];
	$project_login = $project_info[1]['project_login'];
	$project_pass = $project_info[1]['project_pass'];
	
	// name info
	//$project_name = $project_info[1]['project_name'];
	//$project_path = $project_info[1]['project_path'];
	
	$str_connectpage = "<?php\n";
	$str_connectpage .= "\$conn = mysql_connect('$project_server', '$project_login', '$project_pass') or die(mysql_error());\n";
	$str_connectpage .= "mysql_select_db('$project_db',\$conn)  or die(mysql_error());\n";
	
	$str_connectpage .= "
if (get_magic_quotes_gpc()) {
    function stripslashes_deep(\$value)
    {
        \$value = is_array(\$value) ?
                    array_map('stripslashes_deep', \$value) :
                    stripslashes(\$value);

        return \$value;
    }

    \$_POST = array_map('stripslashes_deep', \$_POST);
    \$_GET = array_map('stripslashes_deep', \$_GET);
    \$_COOKIE = array_map('stripslashes_deep', \$_COOKIE);
    \$_REQUEST = array_map('stripslashes_deep', \$_REQUEST);
}

    function dbescape_deep(\$value)
    {
        \$value = is_array(\$value) ?
                    array_map('dbescape_deep', \$value) :
                    mysql_real_escape_string(\$value);

        return \$value;
    }
    \$_POST = array_map('dbescape_deep', \$_POST);
    \$_GET = array_map('dbescape_deep', \$_GET);
    \$_COOKIE = array_map('dbescape_deep', \$_COOKIE);
    \$_REQUEST = array_map('dbescape_deep', \$_REQUEST);
";
	
	
	
	$str_connectpage .= "?>";	
	
	//file_put_contents( $str_connectpage);
	return $str_connectpage;
	
}	


// from Codewalkers By : noisia
/*
* COPY_RECURSIVE_DIRS - copies a directory and all of its contents into a new directory
* @author Noisia from codewalkers
* @param $dirsource
*
*/
function COPY_RECURSIVE_DIRS($dirsource, $dirdest)
{ // recursive function to copy
// all subdirectories and contents:
if(is_dir($dirsource))$dir_handle=opendir($dirsource);
mkdir($dirdest."/".$dirsource, 0750);
while($file=readdir($dir_handle))
{
if($file!="." && $file!="..")
{
if(!is_dir($dirsource."/".$file)) copy ($dirsource."/".$file, $dirdest."/".$dirsource."/".$file);
else COPY_RECURSIVE_DIRS($dirsource."/".$file, $dirdest);
}
}
closedir($dir_handle);
return true;
}

// from php.com
function recurse_copy($src,$dst) {
    $dir = opendir($src);
    @mkdir($dst);
    while(false !== ( $file = readdir($dir)) ) {
        if (( $file != '.' ) && ( $file != '..' )) {
            if ( is_dir($src . '/' . $file) ) {
                recurse_copy($src . '/' . $file,$dst . '/' . $file);
            }
            else {
                copy($src . '/' . $file,$dst . '/' . $file);
            }
        }
    }
    closedir($dir);
}

/**
     * Copy file or folder from source to destination, it can do
     * recursive copy as well and is very smart
     * It recursively creates the dest file or directory path if there weren't exists
     * Situtaions :
     * - Src:/home/test/file.txt ,Dst:/home/test/b ,Result:/home/test/b -> If source was file copy file.txt name with b as name to destination
     * - Src:/home/test/file.txt ,Dst:/home/test/b/ ,Result:/home/test/b/file.txt -> If source was file Creates b directory if does not exsits and copy file.txt into it
     * - Src:/home/test ,Dst:/home/ ,Result:/home/test/** -> If source was directory copy test directory and all of its content into dest     
     * - Src:/home/test/ ,Dst:/home/ ,Result:/home/**-> if source was direcotry copy its content to dest
     * - Src:/home/test ,Dst:/home/test2 ,Result:/home/test2/** -> if source was directoy copy it and its content to dest with test2 as name
     * - Src:/home/test/ ,Dst:/home/test2 ,Result:->/home/test2/** if source was directoy copy it and its content to dest with test2 as name
     * @todo
     *     - Should have rollback technique so it can undo the copy when it wasn't successful
     *  - Auto destination technique should be possible to turn off
     *  - Supporting callback function
     *  - May prevent some issues on shared enviroments : http://us3.php.net/umask
     * @param $source //file or folder
     * @param $dest ///file or folder
     * @param $options //folderPermission,filePermission
     * @return boolean
     */
    function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755))
    {
        $result=false;
       
        if (is_file($source)) {
            if ($dest[strlen($dest)-1]=='/') {
                if (!file_exists($dest)) {
                    cmfcDirectory::makeAll($dest,$options['folderPermission'],true);
                }
                $__dest=$dest."/".basename($source);
            } else {
                $__dest=$dest;
            }
            $result=copy($source, $__dest);
            chmod($__dest,$options['filePermission']);
           
        } elseif(is_dir($source)) {
            if ($dest[strlen($dest)-1]=='/') {
                if ($source[strlen($source)-1]=='/') {
                    //Copy only contents
                } else {
                    //Change parent itself and its contents
                    $dest=$dest.basename($source);
                    @mkdir($dest);
                    chmod($dest,$options['filePermission']);
                }
            } else {
                if ($source[strlen($source)-1]=='/') {
                    //Copy parent directory with new name and all its content
                    @mkdir($dest,$options['folderPermission']);
                    chmod($dest,$options['filePermission']);
                } else {
                    //Copy parent directory with new name and all its content
                    @mkdir($dest,$options['folderPermission']);
                    chmod($dest,$options['filePermission']);
                }
            }

            $dirHandle=opendir($source);
            while($file=readdir($dirHandle))
            {
                if($file!="." && $file!="..")
                {
                     if(!is_dir($source."/".$file)) {
                        $__dest=$dest."/".$file;
                    } else {
                        $__dest=$dest."/".$file;
                    }
                    //echo "$source/$file ||| $__dest<br />";
                    $result=smartCopy($source."/".$file, $__dest, $options);
                }
            }
            closedir($dirHandle);
           
        } else {
            $result=false;
        }
        return $result;
    } 
 
?>